package com.qiu.controller;

import com.qiu.config.OssConfiguration;
import com.qiu.util.general.CommonResult;
import com.qiu.util.oss.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Captain
 */
@Slf4j
@CrossOrigin
@RestController
public class OssController {
    @Autowired
    private OssConfiguration ossConfiguration;

    @RequestMapping("/uploadImage")
    public CommonResult upload(@RequestParam("name") String folderName,
                               @RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return CommonResult.error("文件不能为空");
        }

        try {
            // 生成唯一文件名（避免重复）
            String originalFileName = file.getOriginalFilename();
            String fileExt = originalFileName.substring(originalFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + fileExt;

            // 保存文件到本地目录
            File dest = new File(ossConfiguration.getUPLOAD_DIR() + "/" + folderName + "/" + newFileName);
            // 获取目标文件的父目录
            File parentDir = dest.getParentFile();
            // 确保父目录存在
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs(); // 创建所有缺失的目录（包括多级目录）
            }
            file.transferTo(dest);

            // 返回Nginx可访问的URL
            String fileUrl = ossConfiguration.getNGINX_ACCESS_URL() + "/" + folderName + "/" + newFileName;
            log.info("图片上传成功!");
            return new CommonResult(200, "上传成功", fileUrl);

        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.error("文件上传失败");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error("服务器错误");
        }
    }
}
/*    @RequestMapping("/uploadImage")
    public CommonResult upload(@RequestParam("name") String folderName,
                               @RequestParam("file") MultipartFile file) throws IOException {
        if (file != null) {
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                File newFile = new File(fileName);
                try (FileOutputStream os = new FileOutputStream(newFile)) {
                    os.write(file.getBytes());
                    file.transferTo(newFile);
                    String path = ossUtil.upload(folderName, newFile);
                    log.info("文件上传成功，路径：{}", path);
                    return new CommonResult(200, "上传成功", path);
                } catch (Exception e) {
                    log.error("文件上传失败", e);
                    return CommonResult.error("上传失败");
                } finally {
                    if (newFile.exists()) {
                        FileUtils.forceDelete(newFile);
                    }
                }
            }
        }
        return CommonResult.error("文件不存在");
    }*/